var util = require('../../utils/util.js');
var api = require('../../config/api.js');
const app = getApp()

Page({
    data: {
        // 设备是否为苹果X
        isIphoneX: 0,
        checkedGoodsList: [],
        // 用户默认的收货地址
        checkedAddress: {},
        //商品总价
        goodsTotalPrice: 0,
        //快递费
        freightPrice: 0,
        //订单总价
        orderTotalPrice: 0,
        //实际需要支付的总价
        actualPrice: 0,
        addressId: 0,
        // 商品总数
        goodsCount: 0,
        postscript: '',
        outStock: 0,
        // 支付方式
        payMethodItems: [
            // {
            //     name: 'offline',
            //     value: '线下支付'
            // },
            {
                name: 'online',
                value: '在线支付',
                checked: 'true'
            },
        ],
        payMethod: 1,
        // 购物车id
        cartId: [],
        // 优惠券选择框
        couponsDialog: false,
        // 优惠券列表
        couponsList: [],
        // 选中的优惠券IDs
        couponsIDs: [],
        // 优惠券减免的金额
        cMoney: 0,
        // 抵用券选择框
        vouchersDialog: false,
        // 抵用券列表
        vouchersList: [],
        // 选中的抵用券IDs
        vouchersIDs: [],
        // 抵用券减免的金额
        vMoney: 0,
    },
    onLoad: function (options) {
        let addType = options.addtype;
        let orderFrom = options.orderFrom;
        if (addType != undefined) {
            this.setData({
                addType: addType
            })
        }
        if (orderFrom != undefined) {
            this.setData({
                orderFrom: orderFrom
            })
        }
        // 获取设备信息
        let phone = wx.getStorageSync('isIphoneX')
        if (phone) {
            this.setData({
                isIphoneX: 1
            })
        }
    },
    // 清除本地缓存地址ID
    onUnload: function () {
        wx.removeStorageSync('addressId');
    },
    onShow: function () {
        // 计算商品的总数和商品总价
        this.calculate();
        let addressID = wx.getStorageSync('addressId');
        if (addressID == '' || addressID == undefined) {
            // 获取用户收货地址 显示默认那一条
            this.getUserAddress();
        } else {
            this.setData({
                addressId: addressID
            })
            // 有addressID 获取指定的收货地址
            this.getAddressInfo(addressID);
        }
        // 获取优惠券列表
        this.getCouponsList();
        // 获取抵用券列表
        this.getVouchersList();
    },
    // 切换线上与线下支付
    payChange(e) {
        let val = e.detail.value;
        if (val == 'offline') {
            this.setData({
                payMethod: 0
            })
        } else {
            this.setData({
                payMethod: 1
            })
        }
    },
    // 点击跳转去选择地址界面
    toSelectAddress: function () {
        wx.navigateTo({
            url: '/pages/ucenter/address/index?type=1',
        });
    },
    // 跳转至添加地址界面
    // toAddAddress: function () {
    //     wx.navigateTo({
    //         url: '/pages/ucenter/address-add/index',
    //     })
    // },
    // 点击输入备注
    bindinputMemo(event) {
        let postscript = event.detail.value;
        this.setData({
            postscript: postscript
        });
    },
    // 获取用户收获地址
    getUserAddress() {
        let that = this;
        let userID = wx.getStorageSync('userID')
        util.requestApi(api.getUserAddress, {
            userID: userID
        }).then(function (res) {
            if (res.code == 200) {
                if (res.content[0] == '' || res.content[0] == undefined) {
                    wx.showToast({
                        title: '未添加收货地址',
                        icon: 'success',
                        duration: 2000
                    })
                } else {
                    that.setData({
                        checkedAddress: res.content[0],
                        addressId: res.content[0].id
                    });
                }
                //  计算运费
                that.calculateFreight();
            }
        })
    },
    // 根据地址ID获取选中的地址信息
    getAddressInfo(id) {
        let that = this;
        util.requestApi(api.getAddressInfo, {
            addressID: id
        }).then(function (res) {
            if (res.code == 200) {
                that.setData({
                    checkedAddress: res.content
                })
            }
            // 计算运费
            that.calculateFreight();
            wx.removeStorageSync('addressId');
        })
    },
    // 计算商品数量以及总价（包含运费计算）
    calculate() {
        // 页面显示
        let checkedGoods = app.selectGoods;
        let sumCount = 0;
        let sumPrice = 0;
        let cartID = [],
            idS = [];
        for (let i = 0; i < checkedGoods.length; i++) {
            // 计算商品总件数
            sumCount += checkedGoods[i].goodsNumber;
            // 计算商品总价格
            if (checkedGoods[i].skuHave) {
                sumPrice += checkedGoods[i].goodsNumber * checkedGoods[i].checkedSkuProductInfo.price
            } else {
                sumPrice += checkedGoods[i].goodsNumber * checkedGoods[i].checkedGoods.price;
            }
            // 获取购物车订单ID
            if (checkedGoods[i].checkedGoods.cartID !== '' && checkedGoods[i].checkedGoods.cartID !== undefined) {
                cartID.push(checkedGoods[i].checkedGoods.cartID)
            }
            idS.push(checkedGoods[i].checkedGoods.productID);
        }
        // 保存选中的商品信息，总件数，总价格，以及是否是购物车跳转
        this.setData({
            checkedGoodsList: checkedGoods,
            goodsCount: sumCount,
            goodsTotalPrice: sumPrice,
            freightPrice: 0,
            cartId: cartID,
            productIDS: idS
        });
    },
    // 计算运费
    calculateFreight() {
        let rule = this.data.checkedAddress.rule;
        let sum = this.data.goodsCount;
        if (rule === undefined || sum >= rule.mark) {
            this.setData({
                freightPrice: 0,
                orderTotalPrice: this.data.goodsTotalPrice,
            });
        } else {
            let money = (sum - 1) * rule.round + rule.basis;
            this.setData({
                freightPrice: money,
                orderTotalPrice: this.data.goodsTotalPrice + money,
            });
        }
        // 计算实付总价
        this.countPrice();
    },
    // 下拉刷新 
    onPullDownRefresh: function () {
        wx.showNavigationBarLoading()
        try {
            var addressId = wx.getStorageSync('addressId');
            if (addressId == 0 || addressId == '') {
                addressId = 0;
            }
            this.setData({
                'addressId': addressId
            });
        } catch (e) {
            // Do something when catch error
        }
        this.getCheckoutInfo();
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
    },
    // TODO 有个bug，用户没选择地址，支付无法继续进行，在切换过token的情况下
    // 线上支付
    submitOrder: function (e) {
        let that = this;
        if (that.data.addressId <= 0) {
            util.showErrorToast('请填写收货地址');
            return false;
        }
        let userID = wx.getStorageSync('userID'),
            shareID = wx.getStorageSync('uid');
        let addressId = that.data.addressId;
        let GoodsList = that.data.checkedGoodsList;
        let cartID = that.data.cartId;
        let productList = []
        for (let i = 0; i < GoodsList.length; i++) {
            let everyProductParam = {
                productID: 0,
                count: 0,
                money: 0,
                middleID: '',
                skuPID: [],
                skuID: []
            };
            productList[i] = everyProductParam;
            productList[i].productID = GoodsList[i].checkedGoods.productID;
            productList[i].count = GoodsList[i].goodsNumber;
            if (GoodsList[i].skuHave) {
                productList[i].money = GoodsList[i].checkedSkuProductInfo.price;
                productList[i].skuID = GoodsList[i].checkedSkuProductInfo.skuID;
                productList[i].skuPID = GoodsList[i].checkedSkuProductInfo.skuPID;
                productList[i].middleID = GoodsList[i].checkedSkuProductInfo.middleID;
            } else {
                productList[i].money = GoodsList[i].checkedGoods.price;
                productList[i].skuID = null;
                productList[i].skuPID = null;
                productList[i].middleID = null;
            }
        }
        wx.showModal({
            title: '提示',
            content: '点击确认下单',
            success(res) {
                if (res.confirm) {
                    util.requestApi(api.placeOrder, {
                        addressID: addressId,
                        userID: userID,
                        productList: productList,
                        couponsIDS: that.data.couponsIDs,
                        couponMoney: that.data.cMoney,
                        vouchersMoney: that.data.vMoney,
                        vouchers: that.data.vouchersIDs,
                        postageMoney: that.data.freightPrice,
                        money: that.data.actualPrice,
                        cartIDS: cartID,
                        shareID: shareID ? shareID : 0
                    }).then(function (res) {
                        if (res.code == 200) {
                            let con = res.content
                            wx.requestPayment({
                                timeStamp: con.timeStamp,
                                nonceStr: con.nonceStr,
                                package: con.package,
                                signType: con.signType,
                                paySign: con.paySign,
                                success(res) {
                                    wx.showToast({
                                        title: '下单成功',
                                        icon: 'success',
                                        duration: 2000
                                    })
                                    wx.navigateBack()
                                },
                                fail(res) {
                                    wx.showToast({
                                        title: '下单失败',
                                        icon: 'none',
                                        duration: 2000
                                    })
                                }
                            })
                        } else if (res.code == 201) {
                            wx.showToast({
                                title: '下单成功',
                                icon: 'success',
                                duration: 2000
                            })
                            wx.navigateBack();
                        } else {
                            wx.showToast({
                                title: res.msg,
                                icon: 'none',
                                duration: 2000
                            })
                        }
                    })
                } else if (res.cancel) {
                    wx.showToast({
                        title: '取消下单',
                        icon: 'success',
                        duration: 2000
                    })
                }
            }
        })
    },
    // 线下支付
    offlineOrder: function (e) {

    },
    // 计算实际支付价格
    countPrice() {
        // 获取订单的合计价格（商品总价+运费价格）
        let orderSumMoney = this.data.orderTotalPrice;
        // 优惠券减免的金额
        let cMoney = this.data.cMoney;
        // 抵用券减免的金额
        let vMoney = this.data.vMoney;
        // 获取商品的优惠券以及抵金券价格
        this.setData({
            actualPrice: orderSumMoney - cMoney - vMoney,
        });
    },
    // 获取优惠券列表
    getCouponsList() {
        let that = this
        let userID = wx.getStorageSync('userID');
        let productS = that.data.productIDS;
        util.requestApi(api.getUserCoupons, {
            userID: userID,
            productID: productS
        }).then(function (res) {
            if (res.code == 200) {
                that.setData({
                    couponsList: res.content.data,
                });
            }
        });
    },
    // 获取抵用券列表
    getVouchersList() {
        let that = this
        let userID = wx.getStorageSync('userID');
        let productS = that.data.productIDS;
        util.requestApi(api.getUserVouchers, {
            userID: userID,
            productID: productS
        }).then(function (res) {
            if (res.code == 200) {
                that.setData({
                    vouchersList: res.content.data,
                });
            }
        });
    },
    // 优惠券的选中与取消
    onCouPonsChange(e) {
        let that = this;
        let couList = this.data.couponsList;
        let index = e.currentTarget.dataset.index;
        let id = e.currentTarget.dataset.id;
        let isContains = 0,sum = 0;
        let Goods = app.selectGoods;
        if(!couList[index].checked){
            for (let i = 0; i < Goods.length; i++) {
                if (Goods[i].checkedGoods.productID == id) {
                    for (let j = 0; j < couList.length; j++) {
                        if (couList[j].checked && couList[j].app_coupons.productID == id) {
                            sum += 1;
                        }
                    }
                    if (sum < Goods[i].goodsNumber) {
                        isContains = 1;
                        break;
                    } else {
                        isContains = 2;
                        break;
                    }
                } else if (id == 0) {
                    isContains = 1;
                    break;
                }
            }
            if (isContains == 1) {
                couList[index].checked = !couList[index].checked;
                that.setData({
                    couponsList: couList
                });
            } else if (isContains == 2) {
                wx.showToast({
                    title: '该商品已最大使用',
                    icon: 'none',
                    duration: 1000
                })
            } else {
                wx.showToast({
                    title: '与商品不符',
                    icon: 'none',
                    duration: 1000
                })
            }
        }else{
            couList[index].checked = !couList[index].checked;
            that.setData({
                couponsList: couList
            });
        }
    },
    // 关闭优惠券的选择
    couponDialogClose() {
        let couList = this.data.couponsList;
        let goodsNum = this.data.goodsCount;
        let num = 0;
        let cIDs = [];
        let cMoney = 0;
        for (let i = 0; i < couList.length; i++) {
            if (couList[i].checked) {
                cIDs.push(couList[i].id);
                cMoney += couList[i].app_coupons.money;
                num++;
            }
        }
        if (num > goodsNum) {
            wx.showToast({
                title: '多于商品件数',
                icon: 'none',
                duration: 1000
            });
        } else {
            let list = this.data.vouchersList;
            for (let v = 0; v < list.length; v++) {
                list[v].checked = false;
            }
            this.setData({
                vouchersIDs: [],
                vMoney: 0,
                vouchersList: list,
                couponsDialog: false,
                couponsIDs: cIDs,
                cMoney: cMoney
            });
        }
        // 计算实付金额
        this.countPrice();
    },
    // 打开优惠券
    openCouponsDIalog() {
        this.setData({
            couponsDialog: true
        });
    },
    // 打开抵用券
    openVouchersDIalog() {
        this.setData({
            vouchersDialog: true
        });
    },
    // 关闭抵用券的选择
    vouchersDialogClose() {
        let vouList = this.data.vouchersList;
        let goodsNum = this.data.goodsCount;
        let num = 0;
        let vIDs = [];
        let vMoney = 0;
        for (let i = 0; i < vouList.length; i++) {
            if (vouList[i].checked) {
                vIDs.push(vouList[i].id);
                vMoney += vouList[i].app_vouchers.money;
                num++;
            }
        }
        if (num > goodsNum) {
            wx.showToast({
                title: '多于商品件数',
                icon: 'none',
                duration: 1000
            });
        } else {
            let list = this.data.couponsList;
            for (let c = 0; c < list.length; c++) {
                list[c].checked = false;
            }
            this.setData({
                couponsIDs: [],
                cMoney: 0,
                couponsList: list,
                vouchersDialog: false,
                vouchersIDs: vIDs,
                vMoney: vMoney
            });
        }
        // 计算实付金额
        this.countPrice();
    },
    // 抵用券的选中与取消
    onVouchersChange(e) {
        let vouList = this.data.vouchersList;
        let index = e.currentTarget.dataset.index;
        let id = e.currentTarget.dataset.id
        let isContains = 0,
            sum = 0;
        let Goods = app.selectGoods;
        if (!vouList[index].checked) {
            for (let i = 0; i < Goods.length; i++) {
                if (Goods[i].checkedGoods.productID == id) {
                    for (let j = 0; j < vouList.length; j++) {
                        if (vouList[j].checked && vouList[j].app_vouchers.projectID == id) {
                            sum += 1;
                        }
                    }
                    if (sum < Goods[i].goodsNumber) {
                        isContains = 1;
                        break;
                    } else {
                        isContains = 2;
                        break;
                    }
                }
            }
            if (isContains == 1) {
                vouList[index].checked = !vouList[index].checked;
                this.setData({
                    vouchersList: vouList
                });
            } else if (isContains == 2) {
                wx.showToast({
                    title: '该商品已最大使用',
                    icon: 'none',
                    duration: 1000
                })
            } else {
                wx.showToast({
                    title: '与商品不符',
                    icon: 'none',
                    duration: 1000
                })
            }
        } else {
            vouList[index].checked = !vouList[index].checked;
            this.setData({
                vouchersList: vouList
            });
        }
    },
})